<?php

namespace Home\Controller;
use Think\Controller;

class PublicController extends Controller {
    protected $config = array('app_type' => 'public');

    public function login() {
        $this -> assign("is_verify_code", get_system_config("login_verify_code"));
        $auth_id = session(C('USER_AUTH_KEY'));
        if (!isset($auth_id)) {
            $this -> display();
        } else {
            header('Location: ' . __APP__);
        }
    }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
    function check_verify($code, $id = '') {
        $verify = new \Think\Verify();
        return $verify -> check($code, $id);
    }

    // 登录检测
    public function check_login() {
        $is_verify_code = get_system_config("login_verify_code");
        if (!empty($is_verify_code)) {
            $check = $this -> check_verify($_POST['verify'], 1);
            if (!$check) {
                $this -> error('验证码错误！');
            }
        }

        $emp_no = I('emp_no');
        $password = I('password');
        if (empty($emp_no)) {
            $this -> error('帐号必须！');
        } elseif (empty($password)) {
            $this -> error('密码必须！');
        }

        if ($emp_no == 'admin') {
            $is_admin = true;
            session(C('ADMIN_AUTH_KEY'), true);
        }

        if (C("LDAP_LOGIN") && !$is_admin) {
            if (empty($emp_no)) {
                $this -> error('帐号或密码错误！');
            }

            $ldap_host = C("LDAP_SERVER");
            $ldap_port = C("LDAP_PORT");
            $ldap_user = C("LDAP_USER");

            $ldap_pwd = $password;
            //设定服务器密码
            if (!function_exists('ldap_connect')) {
                $this -> error('请开启LDAP扩展');
            } else {
                $ldap_conn = ldap_connect($ldap_host, $ldap_port);

                ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
                $r = ldap_bind($ldap_conn, $ldap_user, $ldap_pwd);
                //与服务器绑定
                if ($r) {
                    $map['emp_no'] = array('eq', $emp_no);
                    $map["is_del"] = array('eq', 0);
                    $model = M("User");
                    $auth_info = $model -> where($map) -> find();
                } else {
                    $this -> error('LDAP用户验证失败');
                }
            }
        } else {
            $map = array();
            // 支持使用绑定帐号登录
            $map['emp_no'] = array('eq', $emp_no);
            $map["is_del"] = array('eq', 0);
            $map['password'] = array('eq', md5($password));
            $model = M("User");
            $auth_info = $model -> where($map) -> find();
        }

        //使用用户名、密码和状态的方式进行认证
        if (false == $auth_info) {
            $this -> error('帐号或密码错误！');
        } else {

            session('laychat', array('id' => $auth_info['id'], 'username' => $auth_info['name'], 'sign' => $sign, 'avatar' => $auth_info['pic']));

            session(C('USER_AUTH_KEY'), $auth_info['id']);
            session('emp_no', $auth_info['emp_no']);
            session('user_name', $auth_info['name']);
            session('user_pic', $auth_info['pic']);
            session('dept_id', $auth_info['dept_id']);
            session('dept_name', get_dept_name($auth_info['dept_name']));
            session('sub_dept', get_sub_dept($auth_info['dept_id']));
            session('position_id', $auth_info['position_id']);

            //初始密码要求用户修改
            // if (empty($auth_info['init_pwd'])) {
            // $this -> redirect('init_pwd');
            // }
            //保存登录信息

            $User = M('User');
            $ip = get_client_ip();
            $time = time();
            $data = array();
            $data['id'] = $auth_info['id'];
            $data['last_login_time'] = $time;
            $data['login_count'] = array('exp', 'login_count+1');
            $data['last_login_ip'] = $ip;
            $User -> save($data);
            $this -> assign('jumpUrl', U("index/index"));
            header('Location: ' . U("index/index"));
        }
    }

    public function init_pwd() {
        $auth_id = session(C('USER_AUTH_KEY'));
        if (!isset($auth_id)) {
            //跳转到认证网关
            redirect(U(C('USER_AUTH_GATEWAY')));
        }
        $this -> display();
    }

    public function find_pwd() {
        if (IS_POST) {
            $verify_no = I('verify_no');
            if ($verify_no !== session('verify_no')) {
                $this -> error('验证码错误');
            }
            $emp_no = I('emp_no');
            $password = I('password');

            $where['emp_no'] = array('eq', $emp_no);
            $data['password'] = md5($password);
            $result = M("User") -> where($where) -> save($data);
            if ($result !== false) {
                $this -> success('修改密码成功');
                die ;
            } else {
                $this -> success('修改密码失败');
            }
        }
        $this -> display();
    }

    public function send_sms_verify($emp_no) {
        $verify_no = rand_string(6, 1);
        session('verify_no', $verify_no);
        if (empty($emp_no)) {
            $return['info'] = '请输入员工编号';
            $return['status'] = 0;
            $this -> ajaxReturn($return);
        }

        $where_user['emp_no'] = array('eq', $emp_no);
        $user = M("User") -> where($where_user) -> find();

        if ($user == false) {
            $return['info'] = '员工编号不存在';
            $return['status'] = 0;
            $this -> ajaxReturn($return);
        }
        if ($user !== false) {
            if (empty($user['mobile_tel'])) {
                $return['info'] = '该用户手机号不存在，请联系管理员';
                $return['status'] = 0;
                $this -> ajaxReturn($return);
            }
        }

        $account = 'jkwl110';

        //用户密码 $password
        $password = 'jkwl11033';

        //发送到的目标手机号码 $mobile
        $mobile = $user['mobile_tel'];

        //短信内容 $content
        $content = "【SIAS】您的验证码：{$verify_no}";

        //发送短信（其他方法相同）
        $gateway = "http://sh2.ipyy.com/sms.aspx?action=send&userid=&account={$account}&password={$password}&mobile={$mobile}&content={$content}&sendTime=";
        $result = file_get_contents($gateway);
        //dump($result);
        $xml = simplexml_load_string($result);
        if ($xml -> returnstatus == 'Success') {
            $return['status'] = 1;
            $return['info'] = '短信已发送';
            $this -> ajaxReturn($return);
        }
    }

    /* 退出登录 */
    public function logout() {
        $auth_id = session(C('USER_AUTH_KEY'));
        if (isset($auth_id)) {
            session(null);
            cookie(null);
            $this -> assign("jumpUrl", __APP__);
            $this -> success('退出成功！');
        } else {
            $this -> assign("jumpUrl", __APP__);
            $this -> error('退出成功！');
        }
    }

    public function reset_pwd() {
        $password = I('password');
        if ('' == trim($password)) {
            $this -> error('密码不能为空！');
        }

        $data['password'] = md5($password);
        $data['id'] = get_user_id();
        $data['init_pwd'] = 1;

        $result = M('User') -> save($data);

        if (false !== $result) {
            $this -> assign('jumpUrl', get_return_url());
            $this -> success("密码修改成功");
        } else {
            $this -> error('重置密码失败！');
        }
    }

    public function verify() {
        $config = array('fontSize' => 15, // 验证码字体大小
        'length' => 4, // 验证码位数
        'useNoise' => false, // 关闭验证码杂点
        );
        $verify = new \Think\Verify($config);
        $verify -> entry(1);
    }

    function send_sms() {

        header("Content-Type: text/html; charset=utf-8");
        $url = 'http://221.131.83.230:8000/services/cmcc_mas_wbs?wsdl';
        if (!empty($data['type'])) {
            $message .= "[{$data['type']}]";
        }
        if (!empty($data['action'])) {
            $message .= "[{$data['action']}]";
        }
        $message .= "\r\n";
        if (!empty($data['title'])) {
            $message .= "{$data['title']}\r\n";
        }
        if (!empty($data['content'])) {
            $message .= "{$data['content']}";
        }
        //
        //echo $message;

        if (is_array($user_list)) {
            $where['id'] = array('in', $user_list);
        } else {
            $where['id'] = array('eq', $user_list);
        }

        $sms_user_list = M("User") -> getField('mobile_tel', true);
        $sms_user_list = array_filter($sms_user_list);

        foreach ($sms_user_list as $key => &$mobile) {
            $mobile = str_replace('+', '', $mobile);
            $mobile = str_replace('-', '', $mobile);
            $mobile = str_replace(' ', '', $mobile);
            if (empty($mobile)) {
                unset($sms_user_list[$key]);
            } else {
                $mobile = 'tel:' . $mobile;
            }
        }
        //$sms_user_list=implode(",", $sms_user_list);
        $destinationAddresses = $sms_user_list;
        // //自定义扩展代码（模块）
        $ApplicationID = "P000000000000019";
        //
        $destinationAddresses = $sms_user_list;
        //
        // //手机号码
        $paras = array('ApplicationID' => $ApplicationID, 'DestinationAddresses' => $destinationAddresses, 'Message' => $message, 'DeliveryResultRequest' => true, 'MessageFormat' => 'UCS2', 'SendMethod' => 'Long');

        $client = new \soapclient($url);
        try {
            $result = $client -> sendSms($paras);
            if (isset($result -> RequestIdentifier) && strlen(( string )$result -> RequestIdentifier) > 20) {
                return $result -> RequestIdentifier;
            }

        } catch ( Exception $e ) {

        }
    }

}
